package com.cicoding.tcp.client;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.cicoding.service.Uf3sReaderService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Objects;

@Slf4j
@Component
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private Uf3sReaderService uf3sReaderService;

    /**
     * 通道创建就绪后触发
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("client ctx =" + ctx);
        ctx.writeAndFlush(Unpooled.copiedBuffer("Hello, Server!", CharsetUtil.UTF_8));
    }

    /**
     * 当通道有读取事件时，会触发
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

        ByteBuf buf = (ByteBuf) msg;
        String jsonString = buf.toString(CharsetUtil.UTF_8);
        try {


            // 判断字符串最后一位是否是"$"符号
            if (jsonString.endsWith("$")) {
                // 删除末尾的"$"符号
                jsonString = jsonString.substring(0, jsonString.length() - 1);
            }
            JSONObject jsonObject = JSONUtil.parseObj(jsonString);
            String code = jsonObject.getStr("code");
            System.out.println("-------code------:" + code);

            if ("2005".equals(code)) {
                // 读取到2005，自动模式打开
                String rtCode = jsonObject.getStr("rtCode");
                if ("0".equals(rtCode)) {
                    if (Objects.isNull(uf3sReaderService)){
                        uf3sReaderService = SpringUtil.getBean(Uf3sReaderService.class);
                    }
                    uf3sReaderService.setStart(true);
                }
            } else if ("2006".equals(code)) {
                // 读取到2006，自动模式关闭
                String rtCode = jsonObject.getStr("rtCode");
                if ("0".equals(rtCode)) {
                    if (Objects.isNull(uf3sReaderService)){
                        uf3sReaderService = SpringUtil.getBean(Uf3sReaderService.class);
                    }
                    uf3sReaderService.setStart(false);
                }
            }

            System.out.println("服务器回复的消息:" + buf.toString(CharsetUtil.UTF_8));
            System.out.println("服务器的地址： " + ctx.channel().remoteAddress());

        } catch (Exception e) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            log.error("tcp客户端收到消息处理失败，源数据：{}  失败原因：{}", jsonString, baos.toString());

        }

    }

    /**
     * 处理异常, 一般是需要关闭通道
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
